package org.xiaoxin.onecoupon.engine.mq.consumer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.xiaoxin.onecoupon.engine.common.constant.EngineRedisConstant;
import org.xiaoxin.onecoupon.engine.common.context.UserContext;
import org.xiaoxin.onecoupon.engine.common.enums.UserCouponStatusEnum;
import org.xiaoxin.onecoupon.engine.dao.entity.UserCouponDO;
import org.xiaoxin.onecoupon.engine.dao.mapper.UserCouponMapper;
import org.xiaoxin.onecoupon.engine.mq.base.MessageWrapper;
import org.xiaoxin.onecoupon.engine.mq.event.UserCouponDelayCloseEvent;

/**
 * @author xiaoxin
 * 2025/5/12
 */
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = "one-coupon_engine-service_user-coupon-delay-close_topic${unique-name:}",
        consumerGroup = "one-coupon_engine-service_user-coupon-delay-close_cg${unique-name:}"
)
@Slf4j(topic = "UserCouponDelayCloseConsumer")
public class UserConponDelayCloseConsumer implements RocketMQListener<MessageWrapper<UserCouponDelayCloseEvent>> {
   private final StringRedisTemplate stringRedisTemplate;
   private  final UserCouponMapper userCouponMapper;
   @Override
   public void onMessage(MessageWrapper<UserCouponDelayCloseEvent> messageWrapper) {
      // 开头打印日志，平常可 Debug 看任务参数，线上可报平安（比如消息是否消费，重新投递时获取参数等）
      log.info("[消费者] 延迟关闭用户已领取优惠券 - 执行消费逻辑，消息体：{}", JSON.toJSONString(messageWrapper));
      UserCouponDelayCloseEvent event = messageWrapper.getMessage();
      //删除Redis中用户领取优惠劵记录
      String userConponListCacheKey = String.format(EngineRedisConstant.USER_COUPON_TEMPLATE_LIST_KEY, UserContext.getUserId());
      String userConponItemCacheKey = StrUtil.builder()
              .append(event.getCouponTemplateId())
              .append("_")
              .append(event.getUserCouponId())
              .toString();
      Long removed = stringRedisTemplate.opsForZSet().remove(userConponListCacheKey, userConponItemCacheKey);
      if (removed == null||removed == 0){
         return;
      }
      //修改数据库中用户领取优惠劵记录为过期状态
      UserCouponDO userCouponDO = UserCouponDO.builder()
              .status(UserCouponStatusEnum.EXPIRED.getCode())
              .build();
      LambdaUpdateWrapper<UserCouponDO> updateWrapper = Wrappers.lambdaUpdate(UserCouponDO.class)
              .eq(UserCouponDO::getId, event.getUserCouponId())
              .eq(UserCouponDO::getCouponTemplateId, event.getCouponTemplateId())
              .eq(UserCouponDO::getUserId, event.getUserId())
              .eq(UserCouponDO::getStatus, UserCouponStatusEnum.UNUSED.getCode());
      userCouponMapper.update(updateWrapper);

   }
}
